package cn.yujiago.activiti.controller;

import cn.yujiago.activiti.constant.MessageConstant;
import cn.yujiago.activiti.dto.FileResult;
import cn.yujiago.activiti.dto.ResponseEntity;
import cn.yujiago.activiti.entity.User;
import cn.yujiago.activiti.service.WorkflowService;
import cn.yujiago.activiti.util.SessionUtils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

@Controller
public class LCController {

    @Autowired
    @Qualifier("qjlcService")
    private WorkflowService workflowService;

    // 部署流程
    @PostMapping("/deploy/deployByZip")
    @ResponseBody
    public FileResult deployByZip(@RequestParam("file") MultipartFile deployFile){
        FileResult result = null;
        try {
            FileInputStream fis = (FileInputStream) deployFile.getInputStream();
            result = workflowService.saveNewDeploy(fis, deployFile.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
            result = new FileResult(500, MessageConstant.OPT_FAIL);
        }
        return result;
    }

    // 查询部署列表
    @GetMapping("/deploy/deploymentList")
    @ResponseBody
    public String deploymentList(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "10") int limit){
        // 过滤掉不需要的字段
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        filter.getExcludes().add("resources");
        filter.getExcludes().add("persistentState");

        return JSONObject.toJSONString(workflowService.findDeploymentList(page, limit), filter);
    }

    // 查询流程定义列表
    @GetMapping("/deploy/processDefinitionList")
    @ResponseBody
    public String processDefinitionList(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "10") int limit){
        // 过滤掉不需要的字段
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        filter.getExcludes().add("identityLinks");
        filter.getExcludes().add("processDefinition");
        filter.getExcludes().add("tenantId");
        filter.getExcludes().add("executionListeners");
        filter.getExcludes().add("initialActivityStack");
        filter.getExcludes().add("persistentState");

        return JSONObject.toJSONString(workflowService.findProcessDefinitionList(page, limit), filter);
    }

    // 查询流程实例列表
    @GetMapping("/deploy/processInstanceList")
    @ResponseBody
    public String processInstanceList(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "10") int limit){
        // 过滤掉不需要的字段
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        filter.getExcludes().add("persistentState");

        return JSONObject.toJSONString(workflowService.findProcessInstanceList(page, limit), filter);
    }

    // 查询当前用户的任务
    @GetMapping("/deploy/queryTaskByUser")
    @ResponseBody
    public String taskListByUser(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "10") int limit){
        User user = SessionUtils.get();

        // 需要的字段
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        filter.getIncludes().add("id");
        filter.getIncludes().add("assignee");
        filter.getIncludes().add("createTime");
        filter.getIncludes().add("processInstanceId");
        filter.getIncludes().add("processDefinitionId");
        filter.getIncludes().add("taskDefinitionKey");
        filter.getIncludes().add("queryVariables");
        filter.getIncludes().add("processVariables");
        filter.getIncludes().add("name");
        filter.getIncludes().add("code");
        filter.getIncludes().add("msg");
        filter.getIncludes().add("data");
        filter.getIncludes().add("count");

        return JSONObject.toJSONString(workflowService.findTaskListByName(page, limit, user.getUsername()), filter);
    }

    // 获取组列表
    @GetMapping("/deploy/queryGruopList")
    @ResponseBody
    public String gruopList(){
        return JSONObject.toJSONString(workflowService.findGroupList());
    }

    // 查询待拾取组任务
    @GetMapping("/deploy/queryTaskByGroup")
    @ResponseBody
    public String taskListByGroup(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "10") int limit, @RequestParam(value = "groupname", defaultValue = "码农") String groupname){

        // 需要的字段
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        filter.getIncludes().add("id");
        filter.getIncludes().add("assignee");
        filter.getIncludes().add("createTime");
        filter.getIncludes().add("processInstanceId");
        filter.getIncludes().add("processDefinitionId");
        filter.getIncludes().add("taskDefinitionKey");
        filter.getIncludes().add("queryVariables");
        filter.getIncludes().add("processVariables");
        filter.getIncludes().add("name");
        filter.getIncludes().add("code");
        filter.getIncludes().add("msg");
        filter.getIncludes().add("data");
        filter.getIncludes().add("count");

        return JSONObject.toJSONString(workflowService.findTaskListByGroup(page, limit, groupname), filter);
    }

    // 拾取组任务
    @GetMapping("/deploy/takeTask")
    @ResponseBody
    public ResponseEntity takeTask(@RequestParam("taskId") String taskId){
        return workflowService.claimTaskByTaskId(taskId);
    }

    /**
     * 根据流程定义ID，查看流程定义的流程图（以图片的形式显示出来）
     */
    @GetMapping("/deploy/showImg")
    @ResponseBody
    public ResponseEntity showImg(String processDefinitionId, HttpServletResponse response) {
        byte[] b = new byte[1024];
        int len = -1;
        try (
            InputStream inputStream = workflowService.findImageInputStream(processDefinitionId);
            OutputStream outputStream = response.getOutputStream()
        ){
            while ((len = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseEntity.build(200, "查询成功");
    }

    /**
     * 通过任务ID，获取流程图当前活动节点的坐标，用于标出当前活动节点
     */
    @GetMapping("/deploy/viewCurrentImageByTaskId")
    public ModelAndView viewCurrentImageByTaskId(String taskId) {

        Map<String, Object> map = workflowService.getCurrentImageInfoByTaskId(taskId);

        ModelAndView model = new ModelAndView("common/image", map);

        return model;
    }

    /**
     * 通过业务ID，获取流程图当前活动节点的坐标，用于标出当前活动节点
     */
    @GetMapping("/deploy/viewCurrentImageByBusinessKey")
    public ModelAndView viewCurrentImageByBusinessKey(String businessKey) {

        Map<String, Object> map = workflowService.getCurrentImageInfoByBusinessKey(businessKey);

        ModelAndView model = new ModelAndView("common/image", map);

        return model;
    }
}
